package cn.wolfcode.luowowo.website.controller;

import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.cache.util.RedisKeys;
import cn.wolfcode.luowowo.common.exception.LogicException;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.member.service.IUserInfoService;
import cn.wolfcode.luowowo.website.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Controller
public class LoginController {


    //website消费调用  trip-member-api/server  里面接口/实现类
    //消费者与生产者间调用  或者服务与服务间调用
    @Reference //需要调用发布到zookeeper中服务都使用这个
    private IUserInfoService userInfoService;

    @Reference
    private IUserInfoRedisService userInfoRedisService;

    @RequestMapping("/checkPhone")
    @ResponseBody
    public Object checkPhone(String phone) {
        return !userInfoService.checkPhone(phone);
    }

    @RequestMapping("/sendVerifyCode")
    @ResponseBody
    public Object sendVerifyCode(String phone) {


        userInfoService.sendVerifyCode(phone);

        return new AjaxResult();
    }

    @RequestMapping("/userRegist")
    @ResponseBody
    public Object userRegist(String phone, String nickname, String password, String rpassword, String verifyCode) {
        userInfoService.userRegist(phone, nickname, password, rpassword, verifyCode);
        return AjaxResult.success();
    }

    @RequestMapping("/userLogin")
    @ResponseBody
    public Object login(String username, String password, HttpServletResponse response) {
        //获取账号密码进行查询数据user
        UserInfo user = userInfoService.selectByPhoneAndPassword(username, password);
        //如果user对象存在,创建token变量,将这个变量值作为redis的key,user对象作为redis的value值
        if(user == null){
            throw new LogicException("账号或密码错误");
        }

        String token = UUID.randomUUID().toString().substring(0,4);
        userInfoRedisService.setUserLogin(token,user);
        CookieUtil.addCookie(response,"token",token,RedisKeys.USER_LOGIN_TOKEN.getTime().intValue());
        return AjaxResult.success();
    }
}
